<template>
  <div class="mobile-questionnaire-square">
    <van-nav-bar 
      title="问卷广场" 
      left-text="返回"
      left-arrow
      @click-left="goBack"
    >
      <template #right>
        <van-button size="small" type="danger" @click="handleLogout">退出</van-button>
      </template>
    </van-nav-bar>
    
    <div class="content">
      <!-- 搜索栏 -->
      <div class="search-section">
        <van-search
          v-model="searchKeyword"
          placeholder="搜索问卷"
          @search="handleSearch"
          @clear="handleClear"
        />
      </div>
      
      <!-- 分类标签 -->
      <div class="category-section">
        <van-tabs v-model:active="activeCategory" @change="handleCategoryChange">
          <van-tab title="全部" name="all" />
          <van-tab title="热门" name="hot" />
          <van-tab title="最新" name="new" />
          <van-tab title="推荐" name="recommend" />
        </van-tabs>
      </div>
      
      <!-- 问卷列表 -->
      <div class="questionnaire-list">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div 
              v-for="item in questionnaireList" 
              :key="item.id"
              class="questionnaire-item"
              @click="viewQuestionnaire(item)"
            >
              <div class="item-header">
                <h3 class="title">{{ item.title }}</h3>
                <span class="status" :class="item.status">{{ getStatusText(item.status) }}</span>
              </div>
              <p class="description">{{ item.description }}</p>
              <div class="item-footer">
                <span class="author">发布者: {{ item.createBy || '未知' }}</span>
                <span class="date">{{ formatDate(item.createTime) }}</span>
              </div>
              <div class="item-stats">
                <span class="stat">
                  <van-icon name="question-o" />
                  {{ item.questionCount || 0 }}题
                </span>
                <span class="stat">
                  <van-icon name="completed" />
                  {{ item.answerCount || 0 }}份
                </span>
                <span class="stat">
                  <van-icon name="clock-o" />
                  {{ formatDate(item.updateTime) }}
                </span>
              </div>
              <div class="item-actions">
                <van-button size="small" type="primary" @click.stop="viewQuestionnaire(item)">填写问卷</van-button>
              </div>
            </div>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog, showSuccessToast } from 'vant'
import useUserStore from '@/store/modules/user'
import { getQuestionnaireList } from '@/api/questionnaire'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const searchKeyword = ref('')
const activeCategory = ref('all')
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const questionnaireList = ref([])

// 搜索处理
function handleSearch() {
  fetchList()
}

function handleClear() {
  searchKeyword.value = ''
  fetchList()
}

// 分类切换
function handleCategoryChange(name) {
  activeCategory.value = name
  fetchList()
}

// 查看问卷详情
function viewQuestionnaire(item) {
  router.push(`/mobile-questionnaire-detail/${item.id}`)
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    published: '已发布',
    draft: '草稿',
    closed: '已关闭'
  }
  return statusMap[status] || '未知'
}

// 格式化日期
function formatDate(dateStr) {
  const date = new Date(dateStr)
  return `${date.getMonth() + 1}-${date.getDate()}`
}

// 下拉刷新
function onRefresh() {
  refreshing.value = true
  fetchList(() => {
    refreshing.value = false
    showToast('刷新成功')
  })
}

// 上拉加载
function onLoad() {
  loading.value = true
  // 可扩展为分页加载
  fetchList(() => {
    loading.value = false
    finished.value = true // 简单处理，实际可根据返回数据判断
  })
}

// 获取问卷列表
function fetchList(cb) {
  const params = {
    status: 'published', // 只获取已发布的问卷
    keyword: searchKeyword.value,
    pageNum: 1,
    pageSize: 20
  }
  
  // 如果选择了特定分类，添加分类过滤
  if (activeCategory.value !== 'all') {
    params.category = activeCategory.value
  }
  
  getQuestionnaireList(params)
    .then(res => {
      if (res.code === 200) {
        questionnaireList.value = res.rows || []
        // 如果数据为空，显示提示
        if (questionnaireList.value.length === 0) {
          showToast('暂无已发布的问卷')
        }
      } else {
        showToast(res.msg || '加载失败')
      }
      if (cb) cb()
    })
    .catch((error) => {
      console.error('获取问卷列表失败:', error)
      showToast('加载失败，请重试')
      if (cb) cb()
    })
}

// 退出登录
async function handleLogout() {
  try {
    await showConfirmDialog({
      title: '确认退出',
      message: '确定要退出登录吗？退出后需要重新登录。'
    })
    
    // 显示加载状态
    showToast({
      message: '正在退出...',
      duration: 0,
      forbidClick: true
    })
    
    // 调用store的退出登录方法
    await userStore.logOut()
    
    // 清除本地存储的记住密码信息
    const Cookies = await import('js-cookie')
    Cookies.default.remove('username')
    Cookies.default.remove('password')
    Cookies.default.remove('rememberMe')
    
    // 清除其他可能的本地存储
    localStorage.removeItem('vuex')
    sessionStorage.clear()
    
    showSuccessToast('退出成功')
    
    // 跳转到移动端登录页面
    setTimeout(() => {
      router.push('/mobile-login')
    }, 1000)
  } catch (error) {
    if (error) {
      console.error('退出登录失败:', error)
      showToast('退出失败，请重试')
    }
  }
}

// 返回上一页
function goBack() {
  router.back()
}

function goStats(item) {
  router.push(`/mobile-questionnaire-stats/${item.id}`)
}

onMounted(() => {
  // 未登录强制跳转到登录页
  if (!userStore.token) {
    router.replace('/mobile-login')
    return
  }
  fetchList()
})
</script>

<style scoped>
.mobile-questionnaire-square {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.content {
  padding-bottom: 20px;
}

.search-section {
  background: white;
  padding: 8px 0;
}

.category-section {
  background: white;
  margin-bottom: 12px;
}

.questionnaire-list {
  padding: 0 16px;
}

.questionnaire-item {
  background: white;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.questionnaire-item:active {
  transform: scale(0.98);
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.12);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
  flex: 1;
  margin-right: 12px;
}

.status {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status.published {
  background-color: #e8f5e8;
  color: #52c41a;
}

.status.draft {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status.closed {
  background-color: #f5f5f5;
  color: #999;
}

.description {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 16px;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 12px;
  color: #999;
}

.item-stats {
  display: flex;
  gap: 16px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.item-actions {
  margin-top: 8px;
  text-align: right;
}

/* 自定义 Vant 组件样式 */
:deep(.van-nav-bar) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

:deep(.van-nav-bar__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

:deep(.van-nav-bar__text) {
  color: white;
}

:deep(.van-nav-bar .van-button) {
  height: 28px;
  padding: 0 12px;
  font-size: 12px;
  border-radius: 14px;
}

:deep(.van-tabs__line) {
  background-color: #667eea;
}

:deep(.van-tab--active) {
  color: #667eea;
}

:deep(.van-search) {
  padding: 8px 16px;
}

:deep(.van-search__content) {
  border-radius: 20px;
  background-color: #f5f5f5;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .questionnaire-list {
    padding: 0 12px;
  }
  
  .questionnaire-item {
    padding: 16px;
  }
  
  .title {
    font-size: 16px;
  }
}
</style> 